<template>
  <view class="container">
    <image
      src="../../static/login/logo.png"
      class="logo"
      @click="jumpToPage()"
    ></image>

    <!--login 组件-->
    <view class="login-box">
      <LoginCode @childFn="parentFn" />
    </view>
    <view class="login_wx" @click="handleWxLogin">
      <image src="../../static/wechat.png" class="wx"></image>
      <text class="login_wx_text">微信登录</text>
      <image src="../../static/row_r.png" class="arrow"></image>
    </view>
    <view>
      <u-toast ref="uToast" />
    </view>

<!--    <view class="bottom"
      >登录即表明你已同意<text @click="userAgreement()"
        >《壹洽通用户协议》</text
      ></view
    > -->
  </view>
</template>

<script>
import LoginCode from "@/myComponents/sendPhoneCode";

const weixinObj = {
  openid: "oRrdQtyEmjSFRkgi4E1a7Hfc8WPQ",
  nickname: "刘彬",
  sex: 1,
  language: "zh_CN",
  city: "Wuhan",
  province: "Hubei",
  country: "CN",
  headimgurl:
    "https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqEVORhK1JD6cUibTIeQWYXAmia5kJRyo3UHvibNlRE4Gb9ibZTumOpNdCYlrTZqLF1j2gtxjZyeTfBSg/132",
  privilege: [],
  unionid: "oU5Yytzk3YVy_ghlkLOeF9mJ6GP0",
};

export default {
  components: {
    LoginCode,
  },
  data() {
    return {
      weixinObj: {},
      send: true,
      backpage: "",
      backtype: "",
    };
  },

  onLoad(options) {
    this.backpage = options.backpage
      ? options.backpage
      : "../../pages/index/index";
    this.backtype = options.backtype ? options.backtype : 2;
  },

  methods: {
    // 跳转到index
    jumpToPage() {
      uni.switchTab({
        url: "../index/index",
      });
    },

    userAgreement() {
      uni.navigateTo({
        url: "../../pageTwo/document/userAgreement/index",
      });
    },

    parentFn(payload) {
      payload["source"] = "app";
      payload["type"] = "phone";

      // login
      this.$http.post("/api/user/register", payload).then((res) => {
        if (res.data.code == 20000) {
          // token
          uni.setStorageSync(
            "token",
            res.data.token ? res.data.token : res.data.data.token
          );
          // 根据token 获取用户信息
          this.getUserInfo(
            res.data.token ? res.data.token : res.data.data.token
          );
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: "none",
          });
        }
      });
    },

    // token 存储用户信息 header 内放token

    getUserInfo(value) {
      this.$http
        .get("/api/user/token", {
          header: {
            Authorization: value,
          },
        })
        .then((res) => {
          // 存储到缓存

          uni.setStorageSync("userInfo", JSON.stringify(res.data.data));
          //存储用户id
          uni.setStorageSync("userId", res.data.data.id);

          uni.showToast({
            title: "登录成功",
            icon: "none",
          });

          if (this.backtype == 1) {
            uni.redirectTo({
              url: this.backpage,
            });
          } else {
            uni.switchTab({
              url: this.backpage,
            });
          }
        });
    },

    handleWxLogin() {
      // 存入缓存

      var that = this;
      uni.login({
        provider: "weixin",
        success: (loginRes) => {
          let data = loginRes.authResult;

          uni.request({
            url:
              "https://api.weixin.qq.com/sns/userinfo?access_token=" +
              data.access_token +
              "&openid=" +
              data.openid,
            method: "GET",
            dataType: "json",
            header: {
              "content-type": "application/x-www-form-urlencoded", // 默认值
            },
            success: (res) => {
              this.weixinObj = res.data;

              //todo  根据微信返回的unid 判断用户是否第一次登录
              // yes 直接存储 跳转
              // no  输入手机号码授权
              var uniCode = {
                unionid: this.weixinObj.unionid,
              };

              this.$http
                .get("/api/user/register/check", {
                  params: uniCode,
                })
                .then((res) => {
                  if (res.data.data) {
                    if (res.data.data.user.phone) {
                      uni.setStorageSync(
                        "userInfo",
                        JSON.stringify(res.data.data.user)
                      );
                      //存储用户id
                      uni.setStorageSync("userId", res.data.data.user.id);

                      uni.setStorageSync("token", res.data.data.token);

                      this.$refs.uToast.show({
                        title: "登录成功",
                        type: "success",
                        isTab: true,
                        duration: 1000,
                        url: "/pages/index/index",
                      });
                    } else {
                      var sendData = this.weixinObj;
                      sendData["nickName"] = sendData["nickname"];
                      delete ["nickname"];
                      uni.setStorageSync(
                        "weixinInfo",
                        JSON.stringify(this.weixinObj)
                      );
                      uni.navigateTo({
                        url: "../userInfo/checkPhone",
                      });
                    }
                  } else {
                    // 处理数据
                    var sendData = this.weixinObj;
                    sendData["nickName"] = sendData["nickname"];
                    delete ["nickname"];
                    uni.setStorageSync(
                      "weixinInfo",
                      JSON.stringify(this.weixinObj)
                    );
                    uni.navigateTo({
                      url: "../userInfo/checkPhone",
                    });
                  }
                });
            },
          });
        },
        fail: (err) => {
          console.log(err);
          uni.showToast({
            title: "登录失败",
            icon: "none",
            duration: 2000,
          });
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
